<template>
  <el-drawer
    v-model="drawerVisible"
    :destroy-on-close="true"
    size="450px"
    :title="`${drawerProps.title}`"
  >
    <el-tree
      ref="TreeRef"
      class="filter-tree"
      :data="TreeData"
      :props="defaultRightProps"
      show-checkbox
      node-key="key"
      :default-expanded-keys="selectObj.expandedKeys"
      :v-loading="loading"
      :check-strictly="selectObj.association"
      :filter-node-method="filterNode"
      :default-checked-keys="checkedNode"
      @check="handleCheckNodeClick"
    />
    <template #footer>
<!--      <el-select-->
<!--        style="float: left"-->
<!--        v-model="selectObj.selectVal"-->
<!--        @change="selectChange"-->
<!--        placeholder="树操作"-->
<!--      >-->
<!--        <el-option-->
<!--          v-for="item in selectOption"-->
<!--          :key="item.value"-->
<!--          :label="item.label"-->
<!--          :value="item.value"-->
<!--        />-->
<!--      </el-select>-->
      <el-button @click="drawerVisible = false">取消</el-button>
      <el-button type="primary" @click="handleSubmit">确定</el-button>
    </template>
  </el-drawer>
</template>

<script setup lang="ts" name="RoleDrawer">
import { reactive, ref, watch, onMounted, nextTick } from 'vue'
import {
  getQueryRolePermission,
  getQueryTreeList,
  postAddUserRole,
  postSaveRolePermission
} from '@/api/roleManage'
import { ElMessageBox, ElMessage, ElTree } from 'element-plus'
import { selectOption } from '@/views/common'
onMounted(() => {
  getLoadTree()
})
interface DrawerProps {
  title: string
  rowData: { [key: string]: any }
  //   api?: (params: any) => Promise<any>
  //   getTableList?: () => void
}
const defaultRightProps = {
  children: 'children',
  label: 'slotTitle'
}
const TreeData = ref([]) // tree
const loading = ref(false)
const drawerVisible = ref(false)
const drawerProps = ref<DrawerProps>({
  title: '',
  rowData: {}
})
const checkedNode: any = ref([])
const checkedNodeNoDel: any = ref([])
watch(
  () => drawerVisible.value,
  async (newValue) => {
    if (newValue) {
      loading.value = true
      const { id } = drawerProps.value.rowData
      const { result } = await getQueryRolePermission({ roleId: id }).finally(() => {
        loading.value = false
      })
      let res = result
      checkedNodeNoDel.value = [...res]
      let resArr = deleteParentValue(result)
      checkedNode.value = [...resArr]
    }
  }
)
// 去除父级value
const deleteParentValue = (data) => {
    let res = data
    let arr = newRecursion(TreeData.value)
    let arrFather = []
    if( arr.length > 0){
        for(let arri = 0; arri < arr.length; arri++) {
            if (arr[arri].children ? arr[arri].children.length > 0 : false){
                arrFather.push(arr[arri])
            }
        }
        for (let i = 0; i < res.length; i++) {
            for(let item of arrFather){
                if (res[i] == item.value){
                    res.splice(i,1)
                }
            }
        }
    }
    return res
}
// 开始递归
const newRecursion = (data) => {
    let dataArr = []
    let dataItem = []
    for(let i = 0; i < data.length; i++){
        if(data[i].children){
            dataItem = newRecursion(data[i].children)
            if(dataItem.length > 0){
                for (let item of dataItem){
                    if(item){
                        dataArr.push(item)
                    }
                }
            }
        }
        dataArr.push(data[i])
    }
    return dataArr
}
// 接收父组件传过来的参数
const acceptTreeParams = async (params: DrawerProps) => {
  drawerProps.value = params
  await nextTick()
  drawerVisible.value = true
}
interface Tree {
  ID: string
  Name: string
  Children?: Tree[]
}
const checkedKeys = reactive<{
  resultArr: Tree[]
  index: number
}>({
  resultArr: [], // target选择后的数组
  index: 0 // 当前操作的target的index
})
// 选中值发生变化时的回调
const handleCheckNodeClick = (data: Tree, e: any) => {
    console.log('data', data, e)

    selectObj.association = false
    checkedKeys.resultArr = []
    for (let checkedKeysi = 0; checkedKeysi < e.checkedKeys.length; checkedKeysi++ ){
        checkedKeys.resultArr.push(e.checkedKeys[checkedKeysi])
    }
    for (let halfCheckedKeysi = 0; halfCheckedKeysi < e.halfCheckedKeys.length; halfCheckedKeysi++ ){
        checkedKeys.resultArr.push(e.halfCheckedKeys[halfCheckedKeysi])
    }
}
// const handleTarget = (node: any) => {
//   // 递归得到target结果数组
//   if (!node.parent) return
//   checkedKeys.resultArr.unshift(node.data)
//   handleTarget(node.parent)
// }
// 过滤筛选tree
const filterNode = (value: string, data) => {
  if (!value) return true
  return data.title.includes(value)
}
// 获取部门tree
const getLoadTree = async () => {
  const {
    result: { treeList }
  } = await getQueryTreeList()
  TreeData.value = treeList
}
// 提交数据（新增/编辑）
const handleSubmit = async () => {
  ElMessageBox.confirm('是否确认授权?', '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  })
    .then(async () => {
      if (checkedNode.value) {
        try {
          let params = {
            roleId: drawerProps.value.rowData.id,
            permissionIds: checkedKeys.resultArr.join(','),
            lastpermissionIds: checkedNodeNoDel.value.join(',')
          }
          const res = await postSaveRolePermission(params)
          if (res.success) {
            ElMessage.success(res.message)
            drawerVisible.value = false
            checkedNode.value = [] // 解决bug 回显
          } else {
            ElMessage.error(res.message)
          }
        } catch (error) {
          console.log(error)
        }
      }
    })
    .catch(() => {})
}
//select 选项值
const selectObj = reactive({
  //select 值
  selectVal: '',
  //是否关联
  association: false,
  //展开
  expandedKeys: []
})
const TreeRef = ref<InstanceType<typeof ElTree>>()
//选中之后的操作
const selectChange = () => {
  function setAllExpand(state) {
    var nodes = TreeRef.value!.store.nodesMap
    for (var i in nodes) {
      nodes[i].expanded = state
    }
  }
  // console.log(selectObj.selectVal)
  switch (selectObj.selectVal) {
    case '1':
      //父子关联
      selectObj.association = false
      break
    case '2':
      //取消关联
      selectObj.association = true
      break
    case '3':
      //全部勾选
      // console.log(treeRef.value)
      TreeRef.value!.setCheckedNodes(TreeData.value)
      break
    case '4':
      //取消勾选
      TreeRef.value!.setCheckedNodes([])
      break
    case '5':
      //展开所有
      setAllExpand(true)
      break
    case '6':
      //合并所有
      setAllExpand(false)
      break
    default:
      console.log(selectObj.selectVal)
  }
}
defineExpose({
  acceptTreeParams
})
</script>
